<template>
    <div class="app-container">
        <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" label-width="5.3299rem">
            <el-form-item label="活动名称" prop="roleName">
                <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable style="width: 16.4599rem"
                    @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="渠道名称" prop="status">
                <el-select v-model="queryParams.channelId" placeholder="请选择渠道" clearable style="width: 16.4599rem">
                    <el-option v-for="(item, index) in channelSources" :key="index" :value="item.id"
                        :label="item.name" />
                </el-select>
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable style="width: 17.2437rem">
                    <el-option v-for="(dict, index) in sys_normal_disable" :key="index" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="活动类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择活动类型" clearable style="width: 17.2437rem">
                    <el-option v-for="(dict, index) in disable" :key="index" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:role:add']" type="primary" plain icon="Plus"
                    @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:role:edit']" type="success" plain icon="Edit"
                    :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:role:remove']" type="danger" plain icon="Delete" :disabled="multiple"
                    @click="handleDelete()">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:role:export']" type="warning" plain icon="Download"
                    @click="handleExport">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="roleList" @selectionChange="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="活动编号" prop="activityId" width="120" sortable />
            <el-table-column label="活动名称" prop="name" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="渠道名称" prop="channelName" :show-overflow-tooltip="true" width="120" />
            <el-table-column label="活动简介" prop="info" width="100" />
            <el-table-column label="类型" width="100">
                <template #default="scope">
                    <el-button size="small" type="primary" v-if="scope.row.type === 1" plain>折扣券</el-button>
                    <el-button size="small" type="success" v-else plain>代金券</el-button>
                </template>
            </el-table-column>
            <el-table-column label="活动明细" width="100">
                <template #default="scope">
                    <span v-if="scope.row.type === 0">折扣券/{{ scope.row.voucher }}折</span>
                    <span v-else>代金券/{{ scope.row.voucher }}元</span>
                </template>
            </el-table-column>
            <el-table-column label="活动状态" width="100">
                <template #default="scope">
                    <el-button size="small" type="primary" v-if="scope.row.type === 1" plain>正常</el-button>
                    <el-button size="small" type="info" v-else plain>禁用</el-button>
                </template>
            </el-table-column>
            <el-table-column label="活动起始时间" align="center" prop="beginTime">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.beginTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="活动结束时间" align="center" prop="endTime">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.endTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-tooltip v-if="scope.row.roleId !== 1" content="修改" placement="top">
                        <el-button size="small" v-hasPermi="['system:role:edit']" link type="primary" icon="Edit"
                            @click="handleUpdate(scope.row)">修改</el-button>
                    </el-tooltip>
                    <el-tooltip v-if="scope.row.roleId !== 1" content="删除" placement="top">
                        <el-button size="small" v-hasPermi="['system:role:remove']" link type="primary" icon="Delete"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            :total="total" @pagination="getList" />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog v-model="open" :title="title" width="39.1902rem" append-to-body>
            <el-form ref="roleRef" :model="form" :rules="rules" label-width="7.838rem">
                <el-form-item label="渠道来源" prop="status">
                    <el-select v-model="form.channelId" placeholder="渠道来源" clearable style="width: 16.4599rem">
                        <el-option v-for="(item, index) in channelSources" :key="index" :value="item.id"
                            :label="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item label="活动时间" prop="activityTime">
                    <el-date-picker v-model="form.activityTime" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" range-separator="至" format="YYYY-MM-DD HH:mm:ss"
                        date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                </el-form-item>
                <el-form-item label="活动简介" prop="info">
                    <el-input v-model="form.info" placeholder="请输入活动简介" />
                </el-form-item>
                <el-form-item label="活动类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择活动类型" clearable style="width: 16.4599rem">
                        <el-option v-for="item in coupon" :key="item.value" :value="item.value" :label="item.label" />
                    </el-select>
                </el-form-item>
                <!-- 计数器组件 -->
                <el-form-item v-if="counterTitle" label="代金券" prop="voucher">
                    <div class="counter">
                        <h3>{{ counterTitle }}</h3>
                        <el-button @click="form.counterValue--" :disabled="form.counterValue <= 1">减少</el-button>
                        <el-input v-model.number="form.voucher" style="width: 100px; margin: 0 10px;"></el-input>
                        <el-button @click="form.counterValue++">增加</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-if="!form.createBy" type="primary" @click="submitForm">确 定</el-button>
                    <el-button v-else type="primary" @click="addsubitForm">编 辑</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="Role" lang="ts">
/* eslint-disable camelcase */
import {
    listRole,
    deleteId,
    getChannelSources,
    addactivity,
    editactivity
} from '@/api/system/activity';
import { parseTime } from '@/utils/ruoyi';
import { getCurrentInstance, ComponentInternalInstance, watch, ref, reactive, toRefs, nextTick } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;


const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0); // 初始值为0
const title = ref('');
const dateRange = ref<any>([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const menuRef = ref<any>(null);
const roleList = ref<any[]>([]);
const channelSources = ref([]);


// 定义活动状态数组
const sys_normal_disable = ref([
    { value: 0, label: '正常' },
    { value: 1, label: '禁用' }
]);
// 定义活动类型数组
const disable = ref([
    { value: 1, label: '折扣券' },
    { value: 2, label: '代金券' }
]);
const data = reactive<{
    form: any;
    queryParams: any;
    rules: any;
}>({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        type: "",
        status: "",
        channelId: ""
    },
    rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
        roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
    },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
    loading.value = true;
    listRole(proxy!.addDateRange(queryParams.value, dateRange.value))
        .then((response: any) => {
            console.log(response);
            // 更新 roleList 的值
            roleList.value = response.rows;
            console.log(roleList.value);
            total.value = response.total || 0; // 确保 total 始终为 Number 类型
            loading.value = false;
            getChannelSources()
            .then((response: any) => {
                const channelData = response.data.map((item: any) => ({
                    name: item.channelName,
                    id: item.channelId
                }));
                channelSources.value = channelData;
                console.log(channelSources.value);
            });

        }).catch((error: any) => {
            console.error('请求失败:', error);
            total.value = 0; // 请求失败时，将 total 设置为 0
            loading.value = false;
        });
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dateRange.value = [];
    proxy!.resetForm('queryRef');
    handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row: any) {
    let roleIds;
    if (row && row.activityId) {
        roleIds = row.activityId;
    } else if (ids.value && ids.value.length > 0) {
        roleIds = ids.value[0];
    } else {
        proxy!.$modal.msgError('请选择要删除的数据项');
        return;
    }

    proxy!.$modal
        .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
        .then(function () {
            return deleteId(roleIds);
        })
        .then(() => {
            getList();
            proxy!.$modal.msgSuccess('删除成功');
        })
        .catch((e: any) => {
            console.log(e);
        });
}
/** 导出按钮操作 */
function handleExport() {
    proxy!.download(
        'system/role/export',
        {
            ...queryParams.value,
        },
        `role_${new Date().getTime()}.xlsx`
    );
}
/** 多选框选中数据 */
function handleSelectionChange(selection: any[]) {
    console.log(selection[0]);
    if (selection.length > 0) {
        const firstSelectedItem = selection[0];
        console.log(firstSelectedItem.activityId);

        ids.value = [firstSelectedItem.activityId]; // 将 channelId 存储到 ids 中
        single.value = selection.length !== 1;
        multiple.value = selection.length <= 0;
    } else {
        ids.value = [];
        single.value = true;
        multiple.value = true;
    }
}
/** 重置新增的表单以及其他数据  */
function reset() {
    if (menuRef.value) {
        menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: '0',
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined,
        type: undefined,
        counterValue: 0,
        beginTime: "",
        activityTime: [],
        endTime: "",
        info: "",
        name: "",
        voucher: "",
        channelId: "",
        channelName: null,
        createBy: "",
        delFlag: 0,
        discount: 0,
        params: {},
        searchValue: null,
        updateBy: null,
        activityId: ""
    };
    proxy!.resetForm('roleRef');
}
/** 添加活动 */
function submitForm() {
    addactivity(form.value).then((response: any) => {
        proxy!.$modal.msgSuccess('新增成功');
        open.value = false;
        getList();
    }).catch((error) => {
        console.error('请求失败:', error);
        proxy!.$modal.msgError('新增失败');
    })
}

// 定义 coupon 数组
const coupon = ref([
    { value: 0, label: '代金券' },
    { value: 1, label: '折扣券' }
]);
function handleAdd() {
    reset();
    open.value = true;
    title.value = '添加角色';
}
// 定义计数器的状态
const counterTitle = ref('');

// 监听 form.type 的变化
watch(() => form.value.type, (newType) => {
    if (newType === 0) {
        counterTitle.value = '代金券计数器';
    } else if (newType === 1) {
        counterTitle.value = '折扣券计数器';
    } else {
        counterTitle.value = '';
    }
});

// 处理输入数字的变化
const handleChange = (value: number) => {
    console.log('新的值:', value);
    // 这里可以根据需要处理其他逻辑
};
// 把时间分别赋值给俩个参数
import { formdata } from "./hook/format"
watch(() => form.value.activityTime, (newVal) => {
    form.value.activityTime = []
    // console.log(newVal)
    newVal.forEach(el => {
        console.log(el)
        form.value.activityTime.push(formdata.formDate(el))
        console.log(form.value.activityTime);
        form.value.beginTime = form.value.activityTime[0]
        form.value.endTime = form.value.activityTime[1]
        console.log(form.value.beginTime)
        console.log(form.value.endTime)
    });
})
/** 打开修改 */
function handleUpdate(row: any) {
    reset();
    console.log(row);

    // 将 row 的每一项赋值给 form 中对应字段
    for (const key in row) {
        if (form.value.hasOwnProperty(key)) {
            form.value[key] = row[key];
            const activityTime = [
                formdata.formDate(row.beginTime),
                formdata.formDate(row.endTime)
            ]
            form.value.activityTime = activityTime;
        }
    }
    open.value = true;

}
function addsubitForm() {
    editactivity(form.value).then((response: any) => {
        proxy!.$modal.msgSuccess('修改成功');
        open.value = false;
        getList();
    }).catch((error) => {
        console.error('请求失败:', error);
        proxy!.$modal.msgError('修改失败');
    })
}
/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}


/** 取消按钮（数据权限）*/
function cancelDataScope() {
    openDataScope.value = false;
    reset();
}

getList();

</script>

<style scoped>
.counter {
    display: flex;
    align-items: center;
}
</style>
